package com.xh.bussiness.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.course.bean.request.PrepareUserConfigRequest;
import com.xh.bussiness.course.model.PrepareUserConfig;
import com.xh.bussiness.course.dao.PrepareUserConfigMapper;
import com.xh.bussiness.course.service.IPrepareUserConfigService;
import com.xh.bussiness.permission.bean.request.QueryUserRequest;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.model.GlobalPrepareConfigGroup;
import com.xh.bussiness.system.model.GlobalPrepareConfigGroupUser;
import com.xh.bussiness.system.model.UserDataPermission;
import com.xh.bussiness.system.service.IGlobalPrepareConfigGroupService;
import com.xh.bussiness.system.service.IGlobalPrepareConfigGroupUserService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jqm
 * @since 2021-04-02
 */
@Service
public class PrepareUserConfigServiceImpl extends BaseServiceImpl<PrepareUserConfigMapper, PrepareUserConfig> implements IPrepareUserConfigService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGlobalPrepareConfigGroupService globalPrepareConfigGroupService;
    @Autowired
    private IGlobalPrepareConfigGroupUserService globalPrepareConfigGroupUserService;

    @Override
    public XhPage queryPrepareUserConfigPage(XhPage page, PrepareUserConfigRequest bean) {
        Map<String, String> userConfigs = new HashMap<>();
        List<String> userIds = new ArrayList<>();
        List<String> noUserIds = new ArrayList<>();
        QueryWrapper<PrepareUserConfig> qw = new QueryWrapper<>();
        qw.eq("course_id", bean.getCourseId());
        List<PrepareUserConfig> list = super.queryByCondition(qw);
        // 备课设置
        for (PrepareUserConfig prepareUserConfig : list) {
            userConfigs.put(prepareUserConfig.getUserId(), prepareUserConfig.getConfig());
            JSONObject config = JSON.parseObject(prepareUserConfig.getConfig());
            if (bean.getHasPermission() != null) {
                // 查看停用
                if(bean.getHasPermission() ==0 && bean.getHasPermission() == config.getInteger("hasPermission")){
                    userIds.add(prepareUserConfig.getUserId());
                // 查询启用用户
                }else if(bean.getHasPermission() ==1 && 1 != config.getInteger("hasPermission")){
                    noUserIds.add(prepareUserConfig.getUserId());
                }
            }
        }

        if(bean.getHasPermission() != null && bean.getHasPermission() == 0 && userIds.isEmpty()){
            return page;
        }

        // 全局备课设置
        List<GlobalPrepareConfigGroup> globalPrepareConfigGroups = globalPrepareConfigGroupService.queryAll();
        List<GlobalPrepareConfigGroupUser> globalPrepareConfigGroupUsers = globalPrepareConfigGroupUserService.queryAll();
        for (GlobalPrepareConfigGroupUser globalPrepareConfigGroupUser : globalPrepareConfigGroupUsers) {
            String groupId = globalPrepareConfigGroupUser.getGroupId();
            String userId = globalPrepareConfigGroupUser.getUserId();
            if (userConfigs.get(userId) == null) {
                for (GlobalPrepareConfigGroup globalPrepareConfigGroup : globalPrepareConfigGroups) {
                    if(globalPrepareConfigGroup.getId().equals(groupId)){
                        userConfigs.put(userId, globalPrepareConfigGroup.getConfig());
                    }
                }
            }
        }
        GlobalPrepareConfigGroup defaultGroup = globalPrepareConfigGroupService.getById("0");
        QueryUserRequest userBean = new QueryUserRequest();
        userBean.setUsername(bean.getUserName());

        if (!noUserIds.isEmpty()) {
            userBean.setNoUserIds(noUserIds);
        }else if (!userIds.isEmpty()) {
            userBean.setUserIds(userIds);
        }
        page = userService.queryUserPage(page, userBean);
        if (!page.getRecords().isEmpty()) {
            List<Map> users = page.getRecords();
            for (Map user : users) {
                String userId = MapUtils.getString(user, "id");
                user.put("prepareConfig", userConfigs.get(userId) == null ? defaultGroup.getConfig() : userConfigs.get(userId));
            }
        }
        return page;
    }

    @Override
    public List queryPrepareUserConfig(PrepareUserConfigRequest bean) {
        QueryWrapper qw = new QueryWrapper<PrepareUserConfig>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public PrepareUserConfig modifyUserPrepareConfig(PrepareUserConfig prepareUserConfig) {
        QueryWrapper<PrepareUserConfig> qw = new QueryWrapper<>();
        qw.eq("course_id", prepareUserConfig.getCourseId());
        qw.eq("user_id", prepareUserConfig.getUserId());
        PrepareUserConfig oldConfig = super.selectFirst(qw);
        if(oldConfig == null){
            super.insert(prepareUserConfig);
        }else{
            prepareUserConfig.setId(oldConfig.getId());
            super.update(prepareUserConfig);
        }
        return prepareUserConfig;
    }

    @Override
    public List<PrepareUserConfig> batchSetPreparePermission(List<PrepareUserConfig> prepareUserConfigs) {
        if (!prepareUserConfigs.isEmpty()) {
            for (PrepareUserConfig prepareUserConfig : prepareUserConfigs) {
                modifyUserPrepareConfig(prepareUserConfig);
            }
        }
        return prepareUserConfigs;
    }

    @Override
    public String getUserPrepareConfig(String currentUserId, String courseId) {
        QueryWrapper<PrepareUserConfig> qw = new QueryWrapper<>();
        qw.eq("course_id", courseId);
        qw.eq("user_id", currentUserId);
        PrepareUserConfig config = super.selectFirst(qw);
        if(config == null){
            return globalPrepareConfigGroupService.getUserPrepareConfig(currentUserId);
        }
        return config.getConfig();
    }

    @Override
    public List<String> getUserNoPermissionCourseIds(String userId) {
        QueryWrapper<PrepareUserConfig> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.and(wrapper->wrapper.like("config","\"hasPermission\":0").or().like("config","\"hasPermission\":false"));
        List<PrepareUserConfig> list = super.queryByCondition(qw);
        if(list.isEmpty()){
            return new ArrayList<>();
        }
        return list.stream().map(PrepareUserConfig :: getCourseId).collect(Collectors.toList());
    }


    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(PrepareUserConfigRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        return qw;
    }
}
